<?php

namespace app\company\controller;

use app\company\model\CompanyPositionModel;
use app\company\service\PositionService;
use app\exception\MsgException;
use support\Request;
use support\Response;
use think\db\exception\DbException;

/**
 * 职位管理
 * @api
 */
class Position extends Base
{

    /**
     * 获取表格数据
     * @param Request $request
     * @return Response
     * @throws DbException
     * @api
     */
    public function lists(Request $request): Response
    {
        $params = $request->all();
        $service = new PositionService();

        $params['cid'] = $this->getPayload('cid');
        $list = $service->getList($params);
        return $this->withData(0, 'success', $list);
    }

    /**
     * 新增
     * @param Request $request
     * @return Response
     * @throws MsgException
     */
    public function add(Request $request): Response
    {
        $data = $request->all();
        $service = new PositionService();
        if(!empty($data['id'])){
            throw new MsgException("新增数据不可传入ID");
        }

        $data['cid'] = $this->getPayload('cid');
        $res = $service->add($data);
        return $this->withData(0, '新增成功.'.$data['cid'], $res);
    }

    /**
     * 编辑
     * @param Request $request
     * @return Response
     * @throws DbException|MsgException
     */
    public function edit(Request $request): Response
    {
        $data = $request->all();
        $service = new PositionService();

        if($request->method() == 'GET'){
            //职位信息
            $info = CompanyPositionModel::where('id', $data['id'])
                ->with('role')
                ->find();
            //可选权限树
            $ruleTree = $service->getRuleTree();

            return $this->withData(0, 'success', [
                'rules' => $ruleTree,
                'info' => $info
            ]);
        }

        if(empty($data['id'])){
            throw new MsgException("编辑数据需传入ID");
        }
        $res = $service->edit($data);
        return $this->withData(0, '编辑成功', $res);
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     * @throws DbException
     */
    public function delete(Request $request): Response
    {
        $ids = $request->post('ids');
        $service = new PositionService();
        $res = $service->delete($ids);
        return $this->withData(0, '删除成功', $res);
    }

}